const BaseService = require("../base");

class SpuService extends BaseService {
  async getSkuList({ page, limit }) {
    const ctx = this.ctx;
    const skuList = await ctx.model.Product.Sku.find(
      {},
      { skuImageList: 0, skuSaleAttrList: 0, skuAttrList: 0, tmId: 0, category3Id: 0 }
    )
      // .populate("SpuSaleAttrs") // 联表查询
      // .populate("Attrs") // 联表查询
      .skip((page - 1) * limit)
      .limit(limit);

    const total = await ctx.model.Product.Sku.countDocuments();
    // 将_id改为id
    return this.toId({
      records: skuList,
      total,
    });
  }

  async findSkuListBySpuId(spuId) {
    const ctx = this.ctx;
    const skuList = await ctx.model.Product.Sku.find(
      { spuId },
      { skuImageList: 0, skuSaleAttrList: 0, skuAttrList: 0, tmId: 0, category3Id: 0 }
    );
    // 将_id改为id
    return this.toId(skuList);
  }

  async getSkuBySkuId(skuId) {
    const ctx = this.ctx;
    const sku = await ctx.model.Product.Sku.findOne({ _id: skuId });
    return this.toId(sku);
  }

  async saveSku(sku) {
    const ctx = this.ctx;
    await ctx.model.Product.Sku.create(sku);
    return null;
  }

  async updateSku(newSku) {
    const ctx = this.ctx;

    const { id } = newSku;

    const sku = await ctx.model.Product.Sku.findOne({ _id: id, isAdmin: false });
    if (!sku) return false;

    const { skuName, skuDesc, weight, tmId, skuImageList, skuDefaultImg, skuSaleAttrList, skuAttrList, price, skuNum } =
      newSku;

    sku.skuName = skuName;
    sku.skuDesc = skuDesc;
    sku.weight = weight;
    sku.tmId = tmId;
    sku.skuImageList = skuImageList;
    sku.skuDefaultImg = skuDefaultImg;
    sku.skuSaleAttrList = skuSaleAttrList;
    sku.skuAttrList = skuAttrList;
    sku.price = price;
    sku.skuNum = skuNum;

    await sku.save();

    return true;
  }

  async removeSku(id) {
    const ctx = this.ctx;
    const res = await ctx.model.Product.Sku.deleteOne({ _id: id, isAdmin: false });
    // 如果执行成功。会有返回值
    if (res.deletedCount) return true;
    // 如果执行失败，没有返回值
    return false;
  }

  async updateIsSale({ skuId, isSale }) {
    const ctx = this.ctx;
    await ctx.model.Product.Sku.findOneAndUpdate({ _id: skuId }, { isSale });
    return null;
  }
}

module.exports = SpuService;
